package itsm.isperp.module.service.app;

import itsm.isperp.framework.core.context.ContextHolder;
import itsm.isperp.framework.data.dialect.DialectFactory;
import itsm.isperp.framework.data.domain.DataRequest;
import itsm.isperp.framework.data.domain.DataResponse;
import itsm.isperp.framework.data.mybatis.dao.TreeNodeMapper;
import itsm.isperp.framework.ldap.LdapContextUtils;
import itsm.isperp.framework.ldap.synchronize.UnitSync;
import itsm.isperp.framework.service.SyncUnitDataService;
import itsm.isperp.framework.service.TreeNodeService;
import itsm.isperp.module.dto.app.VAppDepartmentUser;
import itsm.isperp.module.entity.app.AppDepartment;
import itsm.isperp.module.entity.app.AppLdapConfig;
import itsm.isperp.module.repository.app.AppDepartmentMapper;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.naming.NamingException;

import org.apache.commons.lang3.StringUtils;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;

/**
 * 系统菜单服务
 * 
 * @author lizx
 * @date 2013-1-12
 * @version V1.0
 */
@Service
public class AppDepartmentService extends TreeNodeService<AppDepartment>
		implements SyncUnitDataService {

	@Resource
	protected AppDepartmentMapper appDepartmentMapper;

	@Override
	public TreeNodeMapper<AppDepartment> getRepository() {
		return this.appDepartmentMapper;
	}

	public DataResponse<VAppDepartmentUser> findAllUserByRequest(DataRequest req) {
		return this.appDepartmentMapper.findAllUserByRequest(req);
	}

	@Override
	public void syncUnitData() throws NamingException {

		AppLdapConfigService appLdapConfigService = ContextHolder
				.getSpringBean("appLdapConfigService");
		List<AppLdapConfig> list = appLdapConfigService.findAll();
		List<String[]> units = new ArrayList<>();
		boolean sync = false;
		for (AppLdapConfig config : list) {
			if (StringUtils.isNotEmpty(config.getSystemOu())) {
				sync = true;
				units.addAll(UnitSync.readData(config.getDc(), config
						.getSystemOu(), LdapContextUtils.getLdapContext(
						config.getHost(), config.getPort(), config.getDc(),
						config.getAdUsername(), config.getAdPassword())));

			}
		}

		if (sync) {
			this.deleteAll();

			JdbcTemplate jdbcTemplate = ContextHolder
					.getSpringBean("jdbcTemplate");
			for (String[] u : units) {
				String sql = "INSERT INTO app_department(id,name,treenode_path,treenode_name_path)VALUES(?,?,?,?)";
				jdbcTemplate.update(sql, "u" + u[2].hashCode(), u[0], u[1],
						u[2]);
			}

			String updateParentIdSql = "UPDATE app_department a INNER JOIN app_department b"
					+ " ON a.treenode_path=b.tdreenode_name_path"
					+ " SET a.parent_id=b.id";

			jdbcTemplate.update(updateParentIdSql);

			jdbcTemplate.execute("CALL sp_treenode_rebuild('app_department');");
		}
	}

	public void batchSave(List<AppDepartment> depts) {
		if (depts != null && depts.size() > 0) {
			for (AppDepartment dept : depts) {
				this.saveOrUpdate(dept);
			}
			this.rebuildTree();
		}

	}
	
	
	public String findDeptByCustomerId(String customerId)
	{
	  JdbcTemplate jdbcTemplate = ContextHolder.getSpringBean("jdbcTemplate");
	  String sql="SELECT * FROM proj_project WHERE cus_customer_id='"+customerId+"'";
	  List<Map<String,Object>> list=jdbcTemplate.queryForList(sql);
	  if(list.size()==1)
	  {
	    
	    String sql2="select * from cus_customer where id='"+customerId+"'";
	    List<Map<String,Object>> list2=jdbcTemplate.queryForList(sql2);
	    if(list2.size()>0)
	    {
	      String deptId_=list2.get(0).get("department_id").toString();
	      return deptId_;
	      
	    }
	    
	  }
	  
	  return null;
	  
	  
	}

	public Map<String,Object> findCusomerDepartment(String departmentId) {
		JdbcTemplate jdbcTemplate = ContextHolder.getSpringBean("jdbcTemplate");
		String sql = "SELECT id,category,name FROM cus_customer";
		if (StringUtils.isEmpty(departmentId)) {
			return null;
		} else {

			AppDepartment dept = this.findOne(departmentId);

			String[] ps = dept.getTreenodePath().split("/");
			String dIds = "";
			for (String s : ps) {
				if (StringUtils.isNotEmpty(s)) {

					dIds += ",'" + s + "'";
				}
			}
			sql += "  WHERE department_id IN(" + dIds.substring(1) + ")";

		}
		try {
			return jdbcTemplate.queryForMap(DialectFactory.getDialect()
					.getLimitString(sql));
		} catch (Exception e) {
			return null;
		}
	}
}
